// miniprogram/pages/info/zmyygzs/zmyygzs.js
var app = getApp();
var util = require('../../../utils/util.js');
var input_id, zy_memo, ticketv = "进出站";
var laifangmudi, beifangzhekeshi, beifangzhename, flag = "1";//wyb住院信息
var sfwc, lxbx4other, zhengzhuang, mz_memo;//门诊信息
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lxbx04zhengzhuangH: true,
    hsfwc: true,
    btnEn: false,
    twocode_en: true,
    ticket: false,
    items: [
      { name: '进出站人员', value: '进出站人员' ,checked:true},
      { name: '买票/问事', value: '买票/问事' },
    ], 
 
  }, 
 
  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {

    this.zmyygzs_lxbx();

    this.lxbx04();
    this.sex_radio();
    this.findOpenid();
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../../chooseLib/chooseLib',
      })
      return
    }

  },

  //拍照或者从相册选择要识别的照片
  photo(type) {
    let that = this

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], ///'original',压缩图
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        let imgUrl = res.tempFilePaths[0];

        that.uploadImg(app.globalData.openid + new Date().getTime(), imgUrl)

      }

    })

  },

  // 上传图片到云存储
  uploadImg(type, imgUrl) {

    let that = this
    wx.cloud.uploadFile({
      cloudPath: 'ocr/' + type + '.png',
      filePath: imgUrl, // 文件路径
      success: res => {
        // console.log("上传成功", res.fileID)
        that.getImgUrl(type, res.fileID)
      },
      fail: err => {
        // console.log("上传失败", err)
      }
    })

  },

  //获取云存储里的图片url
  getImgUrl(type, imgUrl) {
    wx.showToast({
      title: '正在识别',
      icon: 'loading'
    })
    let that = this
    wx.cloud.getTempFileURL({
      fileList: [imgUrl],
      success: res => {
        let imgUrl = res.fileList[0].tempFileURL
        // console.log("获取图片url成功", imgUrl)
        that.shibie(type, imgUrl)
      },
      fail: err => {
        // console.log("获取图片url失败", err)
      }
    })
  },

  //调用云函数，实现OCR识别
  shibie(type, imgUrl) {
    // console.log("识别成功shibie", type)
    let that = this
    wx.cloud.callFunction({
      name: "photo",
      data: {
        type: "shenfenzheng",
        imgUrl: imgUrl
      },
      success(res) {

        switch (res.result.gender) {

          case "男":
            that.setData({
              name: res.result.name,
              sfz: res.result.id,
              address: res.result.addr,
              sex_radio: [{ checked: true, anme: "男", value: "男" },
              { checked: false, anme: "女", value: "女" }]
            })
            break;
          case "女":
            that.setData({
              name: res.result.name,
              sfz: res.result.id,
              address: res.result.addr,
              sex_radio: [{ checked: false, anme: "男", value: "男" },
              { checked: true, anme: "女", value: "女" }]
            })
            break;
        }


      },
      fail(res) {
        // console.log("识别失败", res)
      }
    })
    // console.log("识别成功res.result.name")


  },
  switch1Change :function(e){
    // console.log('马上查询数据库，switch1Change:',e.detail.value)
    if (e.detail.value =="进出站人员"){
      ticketv = "进出站"
      this.setData({
        ticket:false,
        twocode_en: true,
        btnEn: false,
      })
    } else
    {
      ticketv = "买票"
      this.setData({
        ticket: true,
        twocode_en: true,
        btnEn: false,
        startwhere:"",
        crosswhere:"",
        fromwhere:"",
        traininfo:""

      })
    }
   
  }
 ,

  
  lxbx04: function (e) {
    // console.log('马上查询数据库，findcheckbox为:')
    const db = wx.cloud.database();
    var that = this;
    db.collection('checkbox').doc('zmyygzs_lxbx04').get({
      success: function (res) {
        // res.data 包含该记录的数据
        // console.log('findcheckbox为:', res.data.lxbx)
        // console.log('this.data.items为:', res.data.lxbx04)
        that.setData({
          lxbx04zhengzhuang: res.data.lxbx04,
        })
      }
    })
  },


  zmyygzs_lxbx: function (e) {
    // console.log('马上查询数据库，findcheckbox为:')
    const db = wx.cloud.database();
    var that = this;
    db.collection('checkbox').doc('zmyygzs_lxbx').get({
      success: function (res) {
        // res.data 包含该记录的数据
        // console.log('findcheckbox为:', res.data.lxbx)
        // console.log('this.data.items为:', that.data.items)
        that.setData({
          zmyygzs_lxbx: res.data.lxbx,
        })
      }
    })
  },
 
  sex_radio: function (e) {
    // console.log('马上查询数据库，findcheckbox为:')
    const db = wx.cloud.database();
    var that = this;
    db.collection('checkbox').doc('sex').get({
      success: function (res) {
        // console.log('马上查询数据库，findcheckbox为:', res.data.sex)
        that.setData({
          sex_radio: res.data.sex,
        })
      }
    })
  },
  getPhoneNumber(e) {
    var that = this;
    wx.cloud.callFunction({
      name: 'getPhone',
      data: {
        weRunData: wx.cloud.CloudID(e.detail.cloudID),
        twocode_en: true,
        btnEn: false,
      }
    }).then(res => {
      this.setData({
        phone: res.result,
        twocode_en: true,
        btnEn: false,
      })
    }).catch(err => {
    });
  },


  createTwoCode: function () {
    wx.redirectTo({
      url: '/pages/createTwoCode/createTwoCode'
    })
  },
  twocode_en_false: function () {
    // console.log("修改")
    this.setData({
      twocode_en: true,
      btnEn: false,
    })
  },

  findOpenid: function () {
    const db = wx.cloud.database();
    wx.cloud.callFunction({
      name: 'login',
      complete: res => {
        app.globalData.openid = res.result.openid
        db.collection('base_zmyy').where({
          _openid: app.globalData.openid
        }).limit(1)
          .orderBy('addtime', 'desc')//按字段排序
          .get()
          .then(res => {

            // console.log('查询数据库，data:', res.data)
            if (res.data.length) {
              // console.log('查询数据库，data:', res.data[0])
              let arrlxbx = [], arrlxbx04 = [], arrsex = [];  //存放选中id的数组
              let json;
              try {
                if (res.data[0].lxbx != "") {
                  for (let i = 0; i < this.data.zmyygzs_lxbx.length; i++) {
                    if (res.data[0].lxbx.includes(this.data.zmyygzs_lxbx[i].value)) {
                      // 全选获取选中的值
                      json = { "checked": true, "name": this.data.zmyygzs_lxbx[i].name, "value": this.data.zmyygzs_lxbx[i].value }
                      // arrlxbxv.push(json.value)
                    }
                    else {
                      json = { "checked": false, "name": this.data.zmyygzs_lxbx[i].name, "value": this.data.zmyygzs_lxbx[i].value }
                    }
                    arrlxbx.push(json);

                  }
                }
                else {
                  for (let i = 0; i < this.data.zmyygzs_lxbx.length; i++) {

                    json = { "checked": false, "name": this.data.zmyygzs_lxbx[i].name, "value": this.data.zmyygzs_lxbx[i].value }
                    arrlxbx.push(json);
                  }
                }
                this.setData({
                  zmyygzs_lxbx: arrlxbx,
                })
              } catch {

              }


              try {
                if (res.data[0].sex != "") {
                  for (let i = 0; i < this.data.sex_radio.length; i++) {
                    if (res.data[0].sex.includes(this.data.sex_radio[i].name)) {
                      // 全选获取选中的值
                      json = { "checked": true, "name": this.data.sex_radio[i].name, "value": this.data.sex_radio[i].value }
                    }
                    else {
                      json = { "checked": false, "name": this.data.sex_radio[i].name, "value": this.data.sex_radio[i].value }
                    }
                    arrsex.push(json);
                  }
                }
                else {
                  for (let i = 0; i < this.data.sex_radio.length; i++) {
                    json = { "checked": false, "name": this.data.sex_radio[i].name, "value": this.data.sex_radio[i].value }
                    arrsex.push(json);
                  }
                }
                this.setData({
                  sex_radio: arrsex,

                })
              } catch {
              }

              try {
                if (res.data[0].lxbx04zhengzhuang 　!= "") {

                  this.setData({
                    lxbx04zhengzhuangH: false,
                  })
                  for (let i = 0; i < this.data.lxbx04zhengzhuang.length; i++) {
                    if (res.data[0].lxbx04zhengzhuang.includes(this.data.lxbx04zhengzhuang[i].value)) {
                      // 全选获取选中的值
                      json = { "checked": true, "name": this.data.lxbx04zhengzhuang[i].name, "value": this.data.lxbx04zhengzhuang[i].value }
                    }
                    else {
                      json = { "checked": false, "name": this.data.lxbx04zhengzhuang[i].name, "value": this.data.lxbx04zhengzhuang[i].value }
                    }
                    arrlxbx04.push(json);
                  }
                }
                else {
                  this.setData({
                    lxbx04zhengzhuangH: true,
                  })
                  for (let i = 0; i < this.data.lxbx04zhengzhuang.length; i++) {
                    json = { "checked": false, "name": this.data.lxbx04zhengzhuang[i].name, "value": this.data.lxbx04zhengzhuang[i].value }
                    arrlxbx04.push(json);
                  }
                }
                this.setData({
                  lxbx04zhengzhuang: arrlxbx04,
                })
              } catch {

              }

               

              this.setData({
                name: res.data[0].name,
                sex: res.data[0].sex,
                sfz: res.data[0].sfz,
                address: res.data[0].address,
                phone: res.data[0].phone,
                lxbx04qtxx: res.data[0].lxbx04qtxx,
                workaddress: res.data[0].workaddress,
                workphone: res.data[0].workphone,
                startwhere: res.data[0].startwhere,
                crosswhere: res.data[0].crosswhere,
                fromwhere: res.data[0].fromwhere,
                traininfo: res.data[0].traininfo,
                memo: res.data[0].train_memo,
              })
            // 下面住院信息用
              flag = parseInt(res.data[0].flag) + 1,
                zy_memo = res.data[0].zy_memo,
                laifangmudi = res.data[0].laifangmudi,
                beifangzhekeshi = res.data[0].beifangzhekeshi,
                beifangzhename = res.data[0].beifangzhename,
                input_id = res.data[0]._id,
           //门诊登记信息
                sfwc = res.data[0].sfwc,
                lxbx4other = res.data[0].lxbx4other,
                zhengzhuang = res.data[0].zhengzhuang,
                mz_memo = res.data[0].mz_memo

            

              if (res.data[0].name && res.data[0].sfz &&
                res.data[0].sex && res.data[0].address && res.data[0].phone && res.data[0].startwhere && res.data[0].fromwhere
                && res.data[0].traininfo && res.data[0].shiyou !="买票") {
                app.globalData.input_id = "1" + app.globalData.openid
                // console.log('app.globalData.input_id', app.globalData.input_id)

                this.setData({
                  twocode_en: false,
                  btnEn: true,
                })
                if (parseInt(flag) == 2) {
                  // console.log('第二次添加', flag)
                  db.collection('base_zmyy').doc(res.data[0]._id).update({
                    data: {
                      flag: "2",
                    }
                  })
                }
                else {
                  // console.log('不添加', flag)
                }
              }
            }
            else {
              console.log('没查询到数据', res.data.length)
            }
          })

      }
    })


  },
  lxbx: function (e) {
    let zmyygzs_lxbx = e.detail.value
    // console.log("checkbox-group", zmyygzs_lxbx)
    if (zmyygzs_lxbx != "") {
      // console.log("checkbox-true", zmyygzs_lxbx)

      this.setData({
        lxbx04zhengzhuangH: false,
        // lxbx04zhengzhuang: this.data.lxbx04zhengzhuang,
        twocode_en: true,
        btnEn: false,
      })
    }
    else {
      this.lxbx04();
      this.setData({
        lxbx04zhengzhuangH: true,
        twocode_en: true,
        btnEn: false,
      })
    }
  },



  formSubmit: function (e) {
    // console.log('form发生了submit事件，携带数据为：', e.detail.value)
    // this.setData({
    //   btnEn: true,
    // })
    if (
      e.detail.value.name && e.detail.value.sfz && e.detail.value.sex && e.detail.value.address
      ) {
      // console.log('ticketv', ticketv)
      switch (ticketv) {
        case "进出站":
          if (e.detail.value.startwhere && e.detail.value.fromwhere && e.detail.value.traininfo) { 
            if (e.detail.value.phone) {
              const db = wx.cloud.database()
              // console.log('删除数据', input_id)
              try {
                db.collection('base_zmyy').doc(input_id).remove({
                  success: function (res) {
                    // console.log('删除成功', input_id)
                  }
                })
              } catch { }
              // console.log('ticketvsfasd', ticketv)
              db.collection('base_zmyy').add({
                data: {
                  name: e.detail.value.name,
                  sfz: e.detail.value.sfz,
                  sex: e.detail.value.sex,
                  phone: e.detail.value.phone,
                  address: e.detail.value.address,
                  // lxbx: arrlxbxv,
                  lxbx: e.detail.value.lxbx,
                  lxbx04zhengzhuang: e.detail.value.lxbx04zhengzhuang,
                  lxbx04qtxx: e.detail.value.lxbx04qtxx,
                  workaddress: e.detail.value.workaddress,
                  workphone: e.detail.value.workphone,
                  startwhere: e.detail.value.startwhere,
                  crosswhere: e.detail.value.crosswhere,
                  fromwhere: e.detail.value.fromwhere,
                  traininfo: e.detail.value.traininfo,
                  train_memo: e.detail.value.memo,
                  addtime: util.formatTime(new Date()),
                  shiyou: ticketv,
                  // 下面住院信息用
                  zy_memo: zy_memo,
                  laifangmudi: laifangmudi,
                  beifangzhekeshi: beifangzhekeshi,
                  beifangzhename: beifangzhename,
                  flag: flag,
                  //门诊登记信息
                  mz_memo: mz_memo,
                  sfwc: e.detail.value.sfwc,
                  lxbx4other: e.detail.value.lxbx4other,
                  zhengzhuang: e.detail.value.zhengzhuang,
                }
                ,
                success: res => {
                  // 在返回结果中会包含新创建的记录的 _id                  
                  // wx.showToast({
                  //   title: '新增记录成功',
                  // })

                  // console.log('添加数据02', res)
                  app.globalData.input_id = "1" + app.globalData.openid
                  // app.globalData.input_link="station"
                  wx.redirectTo({
                    url: '/pages/createTwoCode/createTwoCode'
                  })
                  this.setData({ btnEn: false })
                },
                fail: err => {
                  wx.showToast({
                    icon: 'none',
                    title: '新增记录失败,请找当值人员手工登记！'
                  })
                  // console.error('[数据库] [新增记录] 失败：', err)
                }
              })

            }
            else {
              // console.log('请更改地址信息：', e.detail.value)
              wx.showToast({
                icon: 'loading',
                title: '请输入手机号',
              })
              this.setData({ btnEn: false, twocode_en: true, })
            }
          }
          else {
            wx.showToast({
              icon: 'loading',
              title: '请填全星号信息',
            })
            this.setData({ btnEn: false, twocode_en: true, })
          }
          break;
        case "买票":
            if (e.detail.value.phone) {
              const db = wx.cloud.database()
              // console.log('删除数据', input_id)
              try {
                db.collection('base_zmyy').doc(input_id).remove({
                  success: function (res) {
                    // console.log('删除成功', input_id)
                  }
                })
              } catch { }
              // console.log('ticketvsfasd', ticketv)
              db.collection('base_zmyy').add({
                data: {
                  name: e.detail.value.name,
                  sfz: e.detail.value.sfz,
                  sex: e.detail.value.sex,
                  phone: e.detail.value.phone,
                  address: e.detail.value.address,
                  // lxbx: arrlxbxv,
                  lxbx: e.detail.value.lxbx,
                  lxbx04zhengzhuang: e.detail.value.lxbx04zhengzhuang,
                  lxbx04qtxx: e.detail.value.lxbx04qtxx,
                  workaddress: e.detail.value.workaddress,
                  workphone: e.detail.value.workphone,
                  startwhere: e.detail.value.startwhere,
                  crosswhere: e.detail.value.crosswhere,
                  fromwhere: e.detail.value.fromwhere,
                  traininfo: e.detail.value.traininfo,
                  train_memo: e.detail.value.memo,
                  addtime: util.formatTime(new Date()),
                  shiyou: ticketv,
                  // 下面住院信息用
                  zy_memo: zy_memo,
                  laifangmudi: laifangmudi,
                  beifangzhekeshi: beifangzhekeshi,
                  beifangzhename: beifangzhename,
                  flag: flag,
                  //门诊登记信息
                  mz_memo: mz_memo,
                  sfwc: e.detail.value.sfwc,
                  lxbx4other: e.detail.value.lxbx4other,
                  zhengzhuang: e.detail.value.zhengzhuang,
                }
                ,
                success: res => {
                  // 在返回结果中会包含新创建的记录的 _id                  
                  // wx.showToast({
                  //   title: '新增记录成功',
                  // })

                  // console.log('添加数据02', res)
                  app.globalData.input_id = "1" + app.globalData.openid
                  // app.globalData.input_link="station"
                  wx.redirectTo({
                    url: '/pages/createTwoCode/createTwoCode'
                  })
                  this.setData({ btnEn: false })
                  ticketv = "进出站"
                },
                fail: err => {
                  wx.showToast({
                    icon: 'none',
                    title: '新增记录失败,请找当值人员手工登记！'
                  })
                  // console.error('[数据库] [新增记录] 失败：', err)
                }
              })

            }
            else {
              // console.log('请更改地址信息：', e.detail.value)
              wx.showToast({
                icon: 'loading',
                title: '请输入手机号',
              })
              this.setData({ btnEn: false, twocode_en: true, })
            }
          
          break;
       
      }
      
     
    }
    else {
      // console.log('form发生了submit事件，携带数据为：', e.detail.value)
      wx.showToast({
        icon: 'loading',
        title: '请填全星号信息',
      })
      this.setData({ btnEn: false, twocode_en: true, })
    }
    // this.setData({ btnEn: false })
  },

})